import sqlite3
import os
from TableProcessor import *
from CommonDef import *
        
class TableManager:
    __slots__ = [
    "__DBName", 
    "__DBHandle", 
    "__TableInfos",
    ];

    def __init__(self):
        self.__DBName = G_Sqlite3DBName;
        self.__TableInfos = {};
        self.__InitDB();
        self.__ReadTables();
        
    def CreateDBTables(self):
        for ExeclTable in self.__TableInfos.values():
            ExeclTable.CreateDBTable();       
        
    def WriteDatasToSqlite(self):
        self.__DBHandle.cursor().execute("BEGIN TRANSACTION") # 关键点
        for ExeclTable in self.__TableInfos.values():
            ExeclTable.WriteDatasToSqlite();
        self.__DBHandle.cursor().execute("COMMIT"); # 关键点
        self.__DBHandle.cursor().close();
        
    def WriteStructsToDotH(self):
        StructsDotHFileHandle = open(G_StructDotHFileName, "w+");
        for ExeclTable in self.__TableInfos.values():
            ExeclTable.WriteStructsToDotH(StructsDotHFileHandle);
        StructsDotHFileHandle.close();
        
        
    def __InitDB(self):
        # delete db if exist
        if os.path.exists(self.__DBName):
            os.remove(self.__DBName);
        self.__DBHandle = sqlite3.connect(self.__DBName, isolation_level=None);

    def __ReadTable(self, _TableName):
        _TableName = G_TablePathPrefix+_TableName;
        ExeclTable = TableProcessor(_TableName, self.__DBHandle);
        PureTableName = ExeclTable.GetTableName();
        if PureTableName in self.__TableInfos:
            print("Error:TableName:%s has exist, please check again!" % (_TableName));
            sys.exit(0);
        else:
            self.__TableInfos[PureTableName] = ExeclTable;
        
    def __ReadTables(self):
        for TableName in TableNameList:
            self.__ReadTable(G_TablePathPrefix+TableName);

        

            
            













